package leetcode.easy.limit200;

import leetcode.ListNode;

public class No160 {
    public static void main(String[] args) {
        ListNode nodeA = ListNode.createByArray(new int[]{1});
        ListNode nodeC = ListNode.createByArray(new int[]{2, 3, 4});
        nodeA.next = nodeC;
        ListNode nodeB = ListNode.createByArray(new int[]{2, 5, 4});
        nodeB.next = nodeC;
        No160 no160 = new No160();
        ListNode intersectionNode = no160.getIntersectionNode(nodeA, nodeB);
        ListNode.print(intersectionNode);
    }

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode p1 = headA;
        ListNode p2 = headB;
        while (p1 != p2) {
            if (p1 == null) {
                p1 = headB;
            } else {
                p1 = p1.next;
            }
            if (p2 == null) {
                p2 = headA;
            } else {
                p2 = p2.next;
            }
        }
        return p1;
    }
}
